<?php
class NewsIndexController  extends Zone_Action{
	protected function fields(){
		$data = array(
			date_updated		=> array(
				type			=> 'NONE',
				default_value	=> mysql_date()
			),		
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),		
			title => array(
				type 		=> 'CHAR',
				no_empty 	=> true,
				form_label 	=> 'Tiêu đề',
				default_value 	=> ''
			),
			desc => array(
				type 	   		=> 'TEXT',
				form_label 		=> 'Mô tả',
				default_value 	=> ''
			),
			content => array(
				type 	   		=> 'TEXT',
				form_label 		=> 'Nội dung',
				default_value 	=> ''
			),
			is_approve => array(
				type 	   		=> 'NONE',
				default_value 	=> 'no'
			),
			parent_id		=> array(
				type		=> 'INT',
				form_label  => 'Loại dự án'				
			),
			date	=> array(
				type		=> 'DATETIME',				
				form_label 	=> 'Ngày hiện',
				no_empty	=> true	
			)
		);
		return $data;	
	}

	protected function notice( $title, $url, $msg ){
		$users = $this->Model->fetchAll("SELECT `ID` FROM `users` WHERE `is_deleted`='no'");		
		foreach( $users as $u ){	
			$this->Model->insert('notices',array(
				created_by_id	=> get_user_id(),
				user_id			=> $u['ID'],
				title			=> $title,
				url				=> $url,
				content			=> $msg,
				date			=> new Model_Expr('NOW()')
			));					
		}	
	}	
	
	public function initAction(){
		$this->set('folders',$this->Model->fetchAll("SELECT * FROM `news_cats` ORDER BY `ord`"));		
		$this->set('user',$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='".get_user_id()."'"));
	}
	
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array("`a`.`is_draft`='no'","`a`.`is_approve`='yes'");
		$current_page = max(getInt('p',1),1);		
		$range_page = 4;//max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}	

		if( !empty($_GET['s'] ) ){
			$word = get('s');
			$vars['s'] = $word;
			$where[] = " CONCAT(`a`.`title`,' ',`a`.`desc`,' ',`a`.`content`) LIKE '%$word%' ";
		}		
			
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
		$where = " WHERE ".implode(' AND ', $where );
		
		$total = $this->Model->fetchOne("SELECT COUNT(*)
				FROM  `news` as `a` $where");
					
		$posts = $this->Model->fetchAll("SELECT `a`.*,
					`b`.`is_deleted`as `created_is_deleted`, 
					`b`.`username`as `created_by_name` 
				FROM  `news` as `a`
				LEFT JOIN `users` as `b`
				ON `b`.`ID`=`a`.`created_by_id`
				$where ORDER BY `a`.`date` DESC $limit");	
		
		$a = $vars;
		unset($a['p']);
		
		$page = page_range('#News?'.to_query_configs($a).'&p=', $current_page, $total , $range_page, 5 );	
		
		$this->set(array(
			total	=> $total,
			page	=> $page,
			posts	=> $posts
		));
	}

	public function topAction(){
		$hots = $this->Model->fetchAll("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`b`.`photo` as `created_by_photo`,
				`c`.`title` as `parent_title`	 
			FROM `news` as `a` 
				LEFT JOIN `users` as `b` 
					ON `a`.`created_by_id`=`b`.`ID`
				LEFT JOIN `news_cats` as `c`
					ON `c`.`ID`=`a`.`parent_id`
			WHERE 
				`a`.`is_draft`='no'
				AND `a`.`date` <= NOW() 
				AND `a`.`is_approve`='yes'
			ORDER BY (1+`a`.total_comment)/TIME(`a`.`date`) DESC LIMIT 0,5");
		
		$comments = $this->Model->fetchAll("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`b`.`photo` as `created_by_photo`,
				`c`.`title` as `parent_title`	
			FROM `news_comments` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			LEFT JOIN `news` as `c`
				ON `c`.`ID`=`a`.`news_id`
			WHERE 
				`a`.`is_draft`='no'				
			ORDER BY `date_created` DESC LIMIT 0,5");			
		
		$this->set(array(
			hots		=> $hots,
			comments	=> $comments
		));			
	}
	
	public function catAction(){
		$user_id = get_user_id();
		$cat_id = getInt('ID',0);		
		$cat   = $this->Model->fetchRow("SELECT * FROM `news_cats` WHERE `ID`='$cat_id'");
		if( !$cat ){
			return $this->setContent(error("Nội dung không tồn tại"));
		}
		
		$posts = $this->Model->fetchAll("SELECT * 
			FROM `news` 
			WHERE
				`date` <= NOW()
				AND `parent_id`='{$cat['ID']}' ORDER BY `date` DESC"); 	
		
		$total = $this->Model->fetchOne("SELECT COUNT(*)
			FROM `news` WHERE `date` <= NOW() AND `parent_id`='{$cat['ID']}'
				AND `is_approve`='yes' 
				AND `is_draft`='no' ORDER BY `date` DESC");

		$current = max(getInt('p',1),1);
		$page = page_range("#News/Index/Cat?ID=$cat_id&p=", $current, $total, 10, 5 );
		
		$this->set(array(
			page	=> $page,
			cat	=> $cat,
			posts	=> $posts
		));
	}
	
	public function viewAction(){
		$news_id = getInt('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`b`.`photo` as `created_by_photo`,
				`c`.`username` as `updated_by_name`,
				`c`.`is_deleted` as `updated_is_deleted`,
				`d`.`title` as `cat_title`
			FROM `news` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c` 
				ON `a`.`updated_by_id`=`c`.`ID`
			LEFT JOIN `news_cats` as `d` 
				ON `a`.`parent_id`=`d`.`ID`
			WHERE `a`.`ID`='$news_id' AND `a`.`is_draft`='no'");			

		if(!$post){
			return $this->setContent(error("Bài viết đã bị xóa hoặc không tồn tại."));
		}
		
		if( $post['is_approve'] == 'no' ){
			return $this->setContent(error("Bài viết chưa được duyệt, hãy quay lại sau."));
		}
		
		$comments = $this->Model->fetchAll("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`b`.`photo` as `created_by_photo` 
			FROM `news_comments` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			WHERE 
				`a`.`news_id`='$news_id' 
				AND `a`.`is_draft`='no'
			ORDER BY `date_created` DESC");
			
		
		$this->Model->update('news',array(
			total_view	=> new Model_Expr('total_view + 1')
		),"`ID`='$news_id'");
		
		$this->set(array(
			post 	=> $post,
			comments	=> $comments
		));	
	}
	
	/* Upload like ajax */
	public function imgAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$id = get("ID",0);
		
		$post = $this->Model->fetchRow("SELECT * FROM `news` WHERE `ID`='$id'");
		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Tin đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( isPost() ){
			loadClass("ZData");
			$f = new ZData();

			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/news/',
					file_type	=> array('gif','png','jpg'),
					no_empty	=> true,
					resize		=> array(150,150)
				)
			));
			
			$data = $f->getData();		
			
			if( is_array( $data ) ){
				$file = $data['file'];
				if( $post['img'] ){
					@unlink("files/news/{$post['img']}");
				}
				
				$this->Model->update("news",array(
					img		=> $file[0]
				),"`ID`='$id'");				
				
				return $this->setJSON(array(
					content	=> "<img src='".baseUrl()."/files/news/{$file[0]}?".time()."'/>"
				));
			}else{
				return $this->setJSON(array(
					alert => $data
				));				
			}			
		}
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}
	
	public function addAction(){
		$user_id = get_user_id();		
		
		$post = $this->Model->fetchRow("SELECT * FROM `news` 
			WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
			
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");	
		$this->set('user',$user);	
			
		if( $post ){
			$news_id = $post['ID'];
			$files = $this->Model->fetchAll("SELECT * FROM `news_files` WHERE `news_id`='$project_id'");	
		}else{
			$this->Model->insert("news",array(
				is_draft		=> 'yes',
				created_by_id	=> $user_id							
			));
			$news_id = $this->Model->lastId();
			$post 	= array(
				ID	=> $news_id
			);
			$files	= array();
		}
		
		$this->set(array(
			user	=> $user,
			post	=> $post,
			files	=> $files
        ));
	
		if(isPost()){		
			$this->removeLayout();			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields() );
			$data = $form->getData();			
			
			if( !is_array( $data )){					
				$this->setJSON(array(
					message => error($data)
				));		
			}
		
			if( !is_array($data) ){
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
			$data['is_draft'] ='no';
			$data['date_created'] = mysql_date();
			$data['created_by_id'] = get_user_id();

			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `news_files` WHERE `news_id`='$news_id'");
			
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete('news_files',"`ID`='{$f['ID']}'");
					@unlink("files/news/{$f['name']}");
				}
			}				
			
			//update data
			$this->Model->update("news",$data,"`ID`='$news_id'");
			$this->setJSON(array(
				redirect =>	"#News/Index/View?ID=$news_id"
			));
		}		
	}	
	
}	